/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package com.wii.elpro.web.action;

import com.wii.elpro.dao.HibernateUtil;
import com.wii.elpro.dao.QuotationDAOInterface;
import com.wii.elpro.dao.SpdcfDAOInterface;
import com.wii.elpro.dao.hb.QuotationDAOImpl;
import com.wii.elpro.dao.hb.SpdcfDAOImpl;
import com.wii.elpro.entity.Quotation;
import com.wii.elpro.entity.QuotationItem;
import com.wii.elpro.entity.SpdcfItem;
import com.wii.elpro.entity.User;
import com.wii.elpro.web.form.QuotationUpdateItemForm;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionMessage;
import org.apache.struts.action.ActionMessages;
import org.apache.struts.actions.DispatchAction;

/**
 *
 * @author hp02
 */
public class QuotationUpdateItemAction extends DispatchAction {
    
    public ActionForward load(ActionMapping mapping, ActionForm form,
            HttpServletRequest request, HttpServletResponse response) throws Exception {
        HttpSession sess = request.getSession(true);
        User user = (User)sess.getAttribute("userSession");       
        if(user==null){
            return mapping.findForward("gagalLogin");            
        }  
        ActionForward af = null;
        QuotationDAOInterface dao = new QuotationDAOImpl();        
        QuotationUpdateItemForm f = (QuotationUpdateItemForm) form;
        Quotation revisedQuotation = new Quotation();
        int index = Integer.parseInt(request.getParameter("id"));
        String scope = request.getParameter("scope");
        ActionMessages messages = null;
        String id;
        if(sess.getAttribute("idQuotation")!=null) {
            id = (String) sess.getAttribute("idQuotation");
        } else {
            id = 0+"";
        }
        try {
            if(sess.getAttribute("idQuotation")!=null) {
                double margin;
                if(scope!=null && scope.equalsIgnoreCase("session")) {
                    List<QuotationItem> items = (List<QuotationItem>) sess.getAttribute("listItem");
                    f.setIndex(index);
                    f.setDisc(items.get(index).getDisc());
                    margin = items.get(index).getPriceHppAndMarginKeuangan()-items.get(index).getProduk().getHargaHpp().getHarga()*items.get(index).getProduk().getWeight();
                    f.setMarginKeuangan((margin*100)/(items.get(index).getProduk().getHargaHpp().getHarga()*items.get(index).getProduk().getWeight()));
                    f.setScope("session");
                } else {
                    Quotation quotation = dao.getQuotation(Long.parseLong((String) sess.getAttribute("idQuotation")));
                    f.setIndex(index);
    //                System.out.println(sess.getAttribute("idProduct"));
    //                System.out.println(p.getNama());
    //                System.out.println("JUMLAH MATERIAL --------> "+p.getProdukMaterials().size());
                    if(sess.getAttribute("revisedQuotation")!=null) {
                        revisedQuotation = (Quotation) sess.getAttribute("revisedQuotation");
                    } else {
                        revisedQuotation = quotation;
                    }
                    f.setDisc(revisedQuotation.getItems().get(index).getDisc());
                    margin = revisedQuotation.getItems().get(index).getPriceHppAndMarginKeuangan()-revisedQuotation.getItems().get(index).getProduk().getHargaHpp().getHarga()*revisedQuotation.getItems().get(index).getProduk().getWeight();
                    f.setMarginKeuangan((margin*100)/(revisedQuotation.getItems().get(index).getProduk().getHargaHpp().getHarga()*revisedQuotation.getItems().get(index).getProduk().getWeight()));
                }
                messages = new ActionMessages();
                messages.add("customMessage", new ActionMessage("customMessage", "You can change quantity of material by filling the text box bellow."));
            } else {
                messages = new ActionMessages();
                messages.add("customMessage", new ActionMessage("customMessage", "Application is fail to retrieve your data. It may caused by missing required variable. Please contact my developer"));
            }
            af = new ActionForward(mapping.findForward("load"));
        } catch (Exception ex) {
            messages = new ActionMessages();
            messages.add("customMessage", new ActionMessage("customMessage", "Application is fail to retrieve your data. Please contact my developer"));
            ex.printStackTrace();
            af = new ActionForward(mapping.findForward("quotation").getPath()+"?id="+id, true);
        }
        saveMessages(sess, messages);
        return af;
    }
    
    // this method has a crosscutting with spdcf. this method can change variable marginKeuangan value
    public ActionForward update(ActionMapping mapping, ActionForm form,
            HttpServletRequest request, HttpServletResponse response) throws Exception {
        HttpSession sess = request.getSession(true);
        User user = (User)sess.getAttribute("userSession");       
        if(user==null){
            return mapping.findForward("gagalLogin");            
        }  
        QuotationUpdateItemForm f = (QuotationUpdateItemForm) form;
        QuotationDAOInterface dao = new QuotationDAOImpl();     
        SpdcfDAOInterface spdcfDao = new SpdcfDAOImpl();
        Quotation revisedQuotation = null;
        Quotation quotation = null;
        ActionMessages messages = null;
        ActionForward af = null;
        String id;
        if(sess.getAttribute("idQuotation")!=null) {
            id = (String) sess.getAttribute("idQuotation");
        } else {
            id = 0+"";
        }
        try {
            // i need quotation here
            quotation = dao.getQuotation(Long.parseLong(id));
            if(sess.getAttribute("revisedQuotation")!=null) {
                quotation.setItems(((Quotation)sess.getAttribute("revisedQuotation")).getItems());
            }
            if(sess.getAttribute("idQuotation")!=null) {
                if(f.getScope().equalsIgnoreCase("session")) {
                    List<QuotationItem> items = (List<QuotationItem>) sess.getAttribute("listItem");
                    items.get(f.getIndex()).setDisc(f.getDisc());
                    // here spdcf margin will be change
                    int x=0;
                    for(SpdcfItem i:quotation.getSpdcf().getItems()) {
                        if(i.getProduk().getId()==items.get(f.getIndex()).getProduk().getId()) {
                            quotation.getSpdcf().getItems().get(x).setMarginKeuangan(f.getMarginKeuangan());
                            break;
                        }
                        x++;
                    }
                    items.get(f.getIndex()).setPriceHppAndMarginKeuangan(items.get(f.getIndex()).getProduk().getHargaHpp().getHarga()*items.get(f.getIndex()).getProduk().getWeight()+(items.get(f.getIndex()).getProduk().getHargaHpp().getHarga()*items.get(f.getIndex()).getProduk().getWeight())*(f.getMarginKeuangan()/100));
                    spdcfDao.update(quotation.getSpdcf());
                } else {
                    quotation.getItems().get(f.getIndex()).setDisc(f.getDisc());
                    // here spdcf margin will be change
                    int x=0;
                    for(SpdcfItem i:quotation.getSpdcf().getItems()) {
                        if(i.getProduk().getId()==quotation.getItems().get(f.getIndex()).getProduk().getId()) {
                            quotation.getSpdcf().getItems().get(x).setMarginKeuangan(f.getMarginKeuangan());
                            break;
                        }
                        x++;
                    }
                    quotation.getItems().get(f.getIndex()).setPriceHppAndMarginKeuangan(quotation.getItems().get(f.getIndex()).getProduk().getHargaHpp().getHarga()*quotation.getItems().get(f.getIndex()).getProduk().getWeight()+(f.getMarginKeuangan()/100)*(quotation.getItems().get(f.getIndex()).getProduk().getHargaHpp().getHarga()*quotation.getItems().get(f.getIndex()).getProduk().getWeight()));
//                    dao.update(quotation);
//                    spdcfDao.update(quotation.getSpdcf());
                    HibernateUtil.getSession().clear();
                    revisedQuotation = quotation;
                    sess.setAttribute("revisedQuotation", revisedQuotation);      
                }
                messages = new ActionMessages();
                messages.add("customMessage", new ActionMessage("customMessage", "Your data is successfully updated (Session state)."));
            } else {
                messages = new ActionMessages();
                messages.add("customMessage", new ActionMessage("customMessage", "Application is fail to retrieve your data. It may caused by missing required variable. Please contact my developer"));
            }
            af = new ActionForward(mapping.findForward("quotation").getPath()+"?id="+id, true);
        } catch (Exception ex) {
            messages = new ActionMessages();
            messages.add("customMessage", new ActionMessage("customMessage", "Application is fail to update your data. Please contact my developer"));
            ex.printStackTrace();
            af = new ActionForward(mapping.findForward("updateItem").getPath()+"?step=load&id="+f.getIndex(), true);
        }
        saveMessages(sess, messages);
        return af;
    }
    
    public ActionForward revise(ActionMapping mapping, ActionForm form,
            HttpServletRequest request, HttpServletResponse response) throws Exception {
        ActionForward af;
        SpdcfDAOInterface spdcfDao = new SpdcfDAOImpl();
        QuotationDAOInterface dao = new QuotationDAOImpl();
        Quotation revisedQuotation = null;
//        Quotation quotation = new Quotation();
        
        ActionMessages messages = new ActionMessages();
        HttpSession sess = request.getSession(true);
        String id;
        if(sess.getAttribute("idQuotation")!=null) {
            id = (String) sess.getAttribute("idQuotation");
        } else {
            id = 0+"";
        }
        try {
            if(sess.getAttribute("revisedQuotation")!=null) {
                revisedQuotation = (Quotation) sess.getAttribute("revisedQuotation");
            }
            
            List<QuotationItem> items = new ArrayList<QuotationItem>();
            QuotationItem item = null;
            for(QuotationItem i:revisedQuotation.getItems()) {
                i.setId(0);
                items.add(i);
            }
            
            revisedQuotation.setId(0);
//            quotation.setDelivery(revisedQuotation.getDelivery());
            revisedQuotation.setItems(items);
//            quotation.setLength(revisedQuotation.getLength());
//            quotation.setLoco(revisedQuotation.getLoco());
//            quotation.setMatrial(revisedQuotation.getMatrial());
//            quotation.setNoQuotation(revisedQuotation.getNoQuotation());
//            quotation.setPaymentTerm(revisedQuotation.getPaymentTerm());
//            quotation.setPositionMatrial(revisedQuotation.getPositionMatrial());
//            quotation.setPrice(revisedQuotation.getPrice());
            revisedQuotation.setRevise(revisedQuotation.getRevise()+1);
//            quotation.setSpdcf(revisedQuotation.getSpdcf());
//            quotation.setStatus(revisedQuotation.getStatus());
//            quotation.setStatusDesc(revisedQuotation.getStatusDesc());
//            quotation.setTglQuotation(revisedQuotation.getTglQuotation());
            revisedQuotation.setTglQuotation(new Date(System.currentTimeMillis()));
//            quotation.setThickness(revisedQuotation.getThickness());
//            quotation.setValidityPrice(revisedQuotation.getValidityPrice());
//            quotation.setValidityStock(revisedQuotation.getValidityStock());
//            quotation.setVat(revisedQuotation.getVat());
            
            dao.save(revisedQuotation);
            spdcfDao.update(revisedQuotation.getSpdcf());
            sess.removeAttribute("revisedQuotation");
            messages.add("customMessage", new ActionMessage("customMessage", "Your data is successfully revised and saved."));
            af = new ActionForward(mapping.findForward("revise"));
        } catch (Exception ex) {
            ex.printStackTrace();
            af = new ActionForward(mapping.findForward("quotation").getPath()+"?id="+id, true);
            messages.add("message", new ActionMessage("customMessage", "Application is fail to save your data. Please contact my developer."));
        }
        saveMessages(sess, messages);
//        af = new ActionForward(mapping.findForward("quotation").getPath()+"?id="+id, true);
        return af;
    }
}
